import { passwordLogin, getUserByToken } from "@/api/admin";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router from '../../router'

const user = {
    state: {
        token: getToken(),
        identity: null, //用户角色 3承兑商6客服9超级用户(平台管理员)
        userId: null, //用户的id
        nickname: null,
        id: null
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_IDENTITY: (state, identity) => {
            state.identity = identity;
        },
        SET_USERID: (state, userId) => {
            state.userId = userId;
        },
        SET_NAME: (state, nickname) => {
            state.nickname = nickname;
        },
        SET_ID: (state, id) => {
            state.id = id;
        },

    },

    actions: {
        // 登录
        Login({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                passwordLogin(userInfo)
                    .then(res => {
                        let data = res.data
                        setToken(data.token);
                        commit("SET_TOKEN", data.token);
                        commit("SET_IDENTITY", data.identity);
                        commit("SET_USERID", data.userId);
                        resolve();
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },


        // 获取用户信息
        GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                let data = {
                    token: state.token
                }
                getUserByToken(data)
                    .then(response => { //
                        console.log("data", response)
                        const data = response.data;
                        localStorage.setItem("identity", data.identity);
                        commit("SET_IDENTITY", data.identity);
                        commit('SET_NAME', data.nickName)
                        commit("SET_USERID", data.userId);
                        commit('SET_ID', data.id)
                        resolve(response);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },


        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                commit("SET_TOKEN", "");
                removeToken();

            });
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit("SET_TOKEN", "");
                removeToken();
                router.push({ path: '/login' })
                resolve();
            });
        }
    }
};

export default user;